package com.etonenet.etpe.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.etonenet.etpe.entity.PhoneApiLog;

@Repository
public class PhoneMapDao {

	private static final String QUERY_ENCODED_PHONE = "select encoded_phone from phone_map where phone= ?";
	private static final String INSERT_INTO_T_PHONE_API_LOG = "insert into t_phone_api_log "
			+ "(log_id,sp_id,batch_id,phone,api_status)" + "values" + "(?,?,?,?,?)";
	@Autowired
	private JdbcTemplate jdbcTemplate;

	/**
	 * JDBC批量插入日志
	 * 
	 * @param phoneApiLogs
	 * 
	 * @return
	 */
	@Transactional
	public int[] batchUpdate(final List<PhoneApiLog> phoneApiLogs) {

		int[] updateCounts = jdbcTemplate.batchUpdate(INSERT_INTO_T_PHONE_API_LOG, new BatchPreparedStatementSetter() {
			public void setValues(PreparedStatement ps, int i) throws SQLException {
				PhoneApiLog phoneApiLog = phoneApiLogs.get(i);
				ps.setLong(1, phoneApiLog.getLogId());
				ps.setLong(2, phoneApiLog.getSpId());
				ps.setLong(3, phoneApiLog.getBatchId());
				ps.setString(4, phoneApiLog.getPhone());
				ps.setInt(5, phoneApiLog.getApiStatus());
			}

			public int getBatchSize() {
				return phoneApiLogs.size();
			}
		});
		return updateCounts;
	}

	public String encodedPhone(String phone) {
		try {
			return jdbcTemplate.queryForObject(QUERY_ENCODED_PHONE, new Object[] { phone }, new RowMapper<String>() {
				@Override
				public String mapRow(ResultSet rs, int rowNum) throws SQLException {
					System.out.println(rowNum);
					if (rs.wasNull()) {
						return null;
					}
					return rs.getString(1);
				}
			});
		} catch (EmptyResultDataAccessException e) {
			// 没有记录时，返回空
			return null;
		}
	}

	/**
	 * 批量查询
	 * 
	 * @param phones
	 * @return
	 * @throws SQLException
	 */
	public List<String> encodedPhone(List<String> phones) throws SQLException {
		Connection conn = jdbcTemplate.getDataSource().getConnection();
		PreparedStatement stmt = conn.prepareStatement(QUERY_ENCODED_PHONE);
		try {
			List<String> encodedPhones = new ArrayList<String>();
			for (String phone : phones) {
				stmt.setString(1, phone);
				ResultSet result = stmt.executeQuery();
				if (result.first()) {
					encodedPhones.add(result.getString(1));
				} else {
					encodedPhones.add(null);
				}
				result.close();
			}
			return encodedPhones;
		} finally {
			stmt.close();
			conn.close();
		}
	}

}
